package top.xinsix.est.controller;

import top.xinsix.est.constants.Constants;
import top.xinsix.est.constants.ResultEnum;
import top.xinsix.est.dto.EvaluateDto;
import top.xinsix.est.dto.MaintainOrderDto;
import top.xinsix.est.dto.UsersDto;
import top.xinsix.est.pojo.Appointment;
import top.xinsix.est.pojo.MaintainOrder;
import top.xinsix.est.req.AppointmentReq;
import top.xinsix.est.service.EvaluateService;
import top.xinsix.est.service.MaintainOrderService;
import top.xinsix.est.service.UsersService;
import top.xinsix.est.tools.Result;
import top.xinsix.est.tools.ResultUtils;
import top.xinsix.est.tools.StringUtil;
import top.xinsix.est.tools.redis.RedisKeyUtils;
import top.xinsix.est.tools.redis.RedisUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("api/order")
public class OrderController {
    @Resource
    private MaintainOrderService orderService;
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private EvaluateService evaluateService;
    @Resource
    private UsersService usersService;

    //维修订单详情
    @GetMapping("/detail/{orderNo}")
    public Result detail(@PathVariable("orderNo") String orderNo, HttpServletRequest request){
        String token = request.getHeader("token");
        MaintainOrderDto orderDto = orderService.getDetailByOrderNo(orderNo);
        return ResultUtils.returnDataSuccess(orderDto);
    }

    @PostMapping("/submit")
    public Result submit(AppointmentReq appointmentReq,Long evaluateId,HttpServletRequest request){
        //获取用户信息
        String token = request.getHeader("token");
        UsersDto users = usersService.getLoginUser(token);
        //校验（验证）
        //1.预约日期校验
        if (!checkAppointDate(appointmentReq.getAppintDate())){
            return ResultUtils.returnFail(ResultEnum.FAIL_PARAM.getCode(),"预约日期不正确");
        }
        //2.预约时间区间校验
        if (!checkTemporalInterval(appointmentReq.getTemporalInterval())){
            return ResultUtils.returnFail(ResultEnum.FAIL_PARAM.getCode(),"预约时间段不正确");
        }
        // 3.手机号校验
        if (!checkPhone(appointmentReq.getPhone())) {
            return ResultUtils.returnFail( ResultEnum.FAIL_PARAM.getCode(),"手机号码错误");
        }
        // 4.短信验证码校验
        if (!checkSmsCode(appointmentReq.getPhone(), Constants.Sms.TYPE_SUBMIT_CHECK, appointmentReq.getSms())) {
            return ResultUtils.returnFail( ResultEnum.FAIL_PARAM.getCode(),"短信验证码错误");
        }
        // 5.地址长度校验(100字以内)
        if (appointmentReq.getAdress().length() > 100) {
            return ResultUtils.returnFail(ResultEnum.FAIL_PARAM.getCode(),"预约地址长度过长");
        }
        // 6.校验评估信息
        EvaluateDto evaluateDto = evaluateService.assessInfo(evaluateId);
        if(evaluateDto == null){
            return ResultUtils.returnResult(ResultEnum.FAIL_HAVE_NOT_EXIST);
        }
        appointmentReq.setUserId(users.getId());
        String orderNo = orderService.submit(appointmentReq, evaluateId, evaluateDto.getModelId());
        Map<String,Object> data = StringUtil.createSimpleMap("orderNo", orderNo);
        return ResultUtils.returnDataSuccess(data);
    }

    private boolean checkTemporalInterval(Integer temporalInterval) {
        if (temporalInterval == Constants.Order.TemporalInterval.AM
                || temporalInterval == Constants.Order.TemporalInterval.NIGHT
                || temporalInterval == Constants.Order.TemporalInterval.NOON
                || temporalInterval == Constants.Order.TemporalInterval.PM){
            return true;
        }
        return false;
    }

    //验证日期
    private boolean checkAppointDate(Date appintDate) {
        if (appintDate != null){
            if (appintDate.getTime() < new Date().getTime()){
                return true;
            }
        }
        return false;
    }
    /**
     * 验证手机号
     * @param phone
     */
    private boolean checkPhone(String phone) {
        boolean flag = false;
        if (!org.apache.commons.lang3.StringUtils.isBlank(phone)) {
            if (phone.length() == 11 && phone.startsWith("1")) {
                flag = true;
            }
        }
        return flag;
    }

    /**
     * 验证验证码
     *
     * @param phone
     * @param codeType
     */
    private boolean checkSmsCode(String phone, Integer codeType, String sms) {
        String value = getVerifyCodeFromRedis(phone,codeType);
        return sms.equals(value);
    }

    /**
     * 从reids中获取验证码
     * @param phone
     * @param codeType
     */
    public String getVerifyCodeFromRedis(String phone ,Integer codeType) {
        String key = RedisKeyUtils.formatKeyWithPrefix(Constants.Redis.PREFIX_SMS, codeType.toString(), phone);
        return redisUtils.getValue(key);
    }
}
